Disregard expired user_group rows in special page and API DB queries
[lhc/web/wiklou.git] / includes / api / ApiQueryAllImages.php
1 <?php
2
3 /**
4 * API for MediaWiki 1.12+
5 *
6 * Created on Mar 16, 2008
7 *
8 * Copyright © 2008 Vasiliev Victor vasilvv@gmail.com,
9 * based on ApiQueryAllPages.php
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 *
26 * @file
27 */
28
29 /**
30 * Query module to enumerate all available pages.
31 *
32 * @ingroup API
33 */
34 class ApiQueryAllImages extends ApiQueryGeneratorBase {
35 protected $mRepo;
36
37 public function __construct( ApiQuery $query, $moduleName ) {
38 parent::__construct( $query, $moduleName, 'ai' );
39 $this->mRepo = RepoGroup::singleton()->getLocalRepo();
40 }
41
42 /**
43 * Override parent method to make sure the repo's DB is used
44 * which may not necessarily be the same as the local DB.
45 *
46 * TODO: allow querying non-local repos.
47 * @return IDatabase
48 */
49 protected function getDB() {
50 return $this->mRepo->getReplicaDB();
51 }
52
53 public function execute() {
54 $this->run();
55 }
56
57 public function getCacheMode( $params ) {
58 return 'public';
59 }
60
61 /**
62 * @param ApiPageSet $resultPageSet
63 * @return void
64 */
65 public function executeGenerator( $resultPageSet ) {
66 if ( $resultPageSet->isResolvingRedirects() ) {
67 $this->dieWithError( 'apierror-allimages-redirect', 'invalidparammix' );
68 }
69
70 $this->run( $resultPageSet );
71 }
72
73 /**
74 * @param ApiPageSet $resultPageSet
75 * @return void
76 */
77 private function run( $resultPageSet = null ) {
78 $repo = $this->mRepo;
79 if ( !$repo instanceof LocalRepo ) {
80 $this->dieWithError( 'apierror-unsupportedrepo' );
81 }
82
83 $prefix = $this->getModulePrefix();
84
85 $db = $this->getDB();
86
87 $params = $this->extractRequestParams();
88
89 // Table and return fields
90 $this->addTables( 'image' );
91
92 $prop = array_flip( $params['prop'] );
93 $this->addFields( LocalFile::selectFields() );
94
95 $ascendingOrder = true;
96 if ( $params['dir'] == 'descending' || $params['dir'] == 'older' ) {
97 $ascendingOrder = false;
98 }
99
100 if ( $params['sort'] == 'name' ) {
101 // Check mutually exclusive params
102 $disallowed = [ 'start', 'end', 'user' ];
103 foreach ( $disallowed as $pname ) {
104 if ( isset( $params[$pname] ) ) {
105 $this->dieWithError(
106 [
107 'apierror-invalidparammix-mustusewith',
108 "{$prefix}{$pname}",
109 "{$prefix}sort=timestamp"
110 ],
111 'invalidparammix'
112 );
113 }
114 }
115 if ( $params['filterbots'] != 'all' ) {
116 $this->dieWithError(
117 [
118 'apierror-invalidparammix-mustusewith',
119 "{$prefix}filterbots",
120 "{$prefix}sort=timestamp"
121 ],
122 'invalidparammix'
123 );
124 }
125
126 // Pagination
127 if ( !is_null( $params['continue'] ) ) {
128 $cont = explode( '|', $params['continue'] );
129 $this->dieContinueUsageIf( count( $cont ) != 1 );
130 $op = ( $ascendingOrder ? '>' : '<' );
131 $continueFrom = $db->addQuotes( $cont[0] );
132 $this->addWhere( "img_name $op= $continueFrom" );
133 }
134
135 // Image filters
136 $from = ( $params['from'] === null ? null : $this->titlePartToKey( $params['from'], NS_FILE ) );
137 $to = ( $params['to'] === null ? null : $this->titlePartToKey( $params['to'], NS_FILE ) );
138 $this->addWhereRange( 'img_name', ( $ascendingOrder ? 'newer' : 'older' ), $from, $to );
139
140 if ( isset( $params['prefix'] ) ) {
141 $this->addWhere( 'img_name' . $db->buildLike(
142 $this->titlePartToKey( $params['prefix'], NS_FILE ),
143 $db->anyString() ) );
144 }
145 } else {
146 // Check mutually exclusive params
147 $disallowed = [ 'from', 'to', 'prefix' ];
148 foreach ( $disallowed as $pname ) {
149 if ( isset( $params[$pname] ) ) {
150 $this->dieWithError(
151 [
152 'apierror-invalidparammix-mustusewith',
153 "{$prefix}{$pname}",
154 "{$prefix}sort=name"
155 ],
156 'invalidparammix'
157 );
158 }
159 }
160 if ( !is_null( $params['user'] ) && $params['filterbots'] != 'all' ) {
161 // Since filterbots checks if each user has the bot right, it
162 // doesn't make sense to use it with user
163 $this->dieWithError(
164 [ 'apierror-invalidparammix-cannotusewith', "{$prefix}user", "{$prefix}filterbots" ]
165 );
166 }
167
168 // Pagination
169 $this->addTimestampWhereRange(
170 'img_timestamp',
171 $ascendingOrder ? 'newer' : 'older',
172 $params['start'],
173 $params['end']
174 );
175 // Include in ORDER BY for uniqueness
176 $this->addWhereRange( 'img_name', $ascendingOrder ? 'newer' : 'older', null, null );
177
178 if ( !is_null( $params['continue'] ) ) {
179 $cont = explode( '|', $params['continue'] );
180 $this->dieContinueUsageIf( count( $cont ) != 2 );
181 $op = ( $ascendingOrder ? '>' : '<' );
182 $continueTimestamp = $db->addQuotes( $db->timestamp( $cont[0] ) );
183 $continueName = $db->addQuotes( $cont[1] );
184 $this->addWhere( "img_timestamp $op $continueTimestamp OR " .
185 "(img_timestamp = $continueTimestamp AND " .
186 "img_name $op= $continueName)"
187 );
188 }
189
190 // Image filters
191 if ( !is_null( $params['user'] ) ) {
192 $this->addWhereFld( 'img_user_text', $params['user'] );
193 }
194 if ( $params['filterbots'] != 'all' ) {
195 $this->addTables( 'user_groups' );
196 $this->addJoinConds( [ 'user_groups' => [
197 'LEFT JOIN',
198 [
199 'ug_group' => User::getGroupsWithPermission( 'bot' ),
200 'ug_user = img_user',
201 'ug_expiry IS NULL OR ug_expiry >=' . $db->addQuotes( $db->timestamp() )
202 ]
203 ] ] );
204 $groupCond = ( $params['filterbots'] == 'nobots' ? 'NULL' : 'NOT NULL' );
205 $this->addWhere( "ug_group IS $groupCond" );
206 }
207 }
208
209 // Filters not depending on sort
210 if ( isset( $params['minsize'] ) ) {
211 $this->addWhere( 'img_size>=' . intval( $params['minsize'] ) );
212 }
213
214 if ( isset( $params['maxsize'] ) ) {
215 $this->addWhere( 'img_size<=' . intval( $params['maxsize'] ) );
216 }
217
218 $sha1 = false;
219 if ( isset( $params['sha1'] ) ) {
220 $sha1 = strtolower( $params['sha1'] );
221 if ( !$this->validateSha1Hash( $sha1 ) ) {
222 $this->dieWithError( 'apierror-invalidsha1hash' );
223 }
224 $sha1 = Wikimedia\base_convert( $sha1, 16, 36, 31 );
225 } elseif ( isset( $params['sha1base36'] ) ) {
226 $sha1 = strtolower( $params['sha1base36'] );
227 if ( !$this->validateSha1Base36Hash( $sha1 ) ) {
228 $this->dieWithError( 'apierror-invalidsha1base36hash' );
229 }
230 }
231 if ( $sha1 ) {
232 $this->addWhereFld( 'img_sha1', $sha1 );
233 }
234
235 if ( !is_null( $params['mime'] ) ) {
236 if ( $this->getConfig()->get( 'MiserMode' ) ) {
237 $this->dieWithError( 'apierror-mimesearchdisabled' );
238 }
239
240 $mimeConds = [];
241 foreach ( $params['mime'] as $mime ) {
242 list( $major, $minor ) = File::splitMime( $mime );
243 $mimeConds[] = $db->makeList(
244 [
245 'img_major_mime' => $major,
246 'img_minor_mime' => $minor,
247 ],
248 LIST_AND
249 );
250 }
251 // safeguard against internal_api_error_DBQueryError
252 if ( count( $mimeConds ) > 0 ) {
253 $this->addWhere( $db->makeList( $mimeConds, LIST_OR ) );
254 } else {
255 // no MIME types, no files
256 $this->getResult()->addValue( 'query', $this->getModuleName(), [] );
257 return;
258 }
259 }
260
261 $limit = $params['limit'];
262 $this->addOption( 'LIMIT', $limit + 1 );
263 $sortFlag = '';
264 if ( !$ascendingOrder ) {
265 $sortFlag = ' DESC';
266 }
267 if ( $params['sort'] == 'timestamp' ) {
268 $this->addOption( 'ORDER BY', 'img_timestamp' . $sortFlag );
269 if ( !is_null( $params['user'] ) ) {
270 $this->addOption( 'USE INDEX', [ 'image' => 'img_usertext_timestamp' ] );
271 } else {
272 $this->addOption( 'USE INDEX', [ 'image' => 'img_timestamp' ] );
273 }
274 } else {
275 $this->addOption( 'ORDER BY', 'img_name' . $sortFlag );
276 }
277
278 $res = $this->select( __METHOD__ );
279
280 $titles = [];
281 $count = 0;
282 $result = $this->getResult();
283 foreach ( $res as $row ) {
284 if ( ++$count > $limit ) {
285 // We've reached the one extra which shows that there are
286 // additional pages to be had. Stop here...
287 if ( $params['sort'] == 'name' ) {
288 $this->setContinueEnumParameter( 'continue', $row->img_name );
289 } else {
290 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
291 }
292 break;
293 }
294
295 if ( is_null( $resultPageSet ) ) {
296 $file = $repo->newFileFromRow( $row );
297 $info = array_merge( [ 'name' => $row->img_name ],
298 ApiQueryImageInfo::getInfo( $file, $prop, $result ) );
299 self::addTitleInfo( $info, $file->getTitle() );
300
301 $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $info );
302 if ( !$fit ) {
303 if ( $params['sort'] == 'name' ) {
304 $this->setContinueEnumParameter( 'continue', $row->img_name );
305 } else {
306 $this->setContinueEnumParameter( 'continue', "$row->img_timestamp|$row->img_name" );
307 }
308 break;
309 }
310 } else {
311 $titles[] = Title::makeTitle( NS_FILE, $row->img_name );
312 }
313 }
314
315 if ( is_null( $resultPageSet ) ) {
316 $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'img' );
317 } else {
318 $resultPageSet->populateFromTitles( $titles );
319 }
320 }
321
322 public function getAllowedParams() {
323 $ret = [
324 'sort' => [
325 ApiBase::PARAM_DFLT => 'name',
326 ApiBase::PARAM_TYPE => [
327 'name',
328 'timestamp'
329 ]
330 ],
331 'dir' => [
332 ApiBase::PARAM_DFLT => 'ascending',
333 ApiBase::PARAM_TYPE => [
334 // sort=name
335 'ascending',
336 'descending',
337 // sort=timestamp
338 'newer',
339 'older'
340 ]
341 ],
342 'from' => null,
343 'to' => null,
344 'continue' => [
345 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
346 ],
347 'start' => [
348 ApiBase::PARAM_TYPE => 'timestamp'
349 ],
350 'end' => [
351 ApiBase::PARAM_TYPE => 'timestamp'
352 ],
353 'prop' => [
354 ApiBase::PARAM_TYPE => ApiQueryImageInfo::getPropertyNames( $this->propertyFilter ),
355 ApiBase::PARAM_DFLT => 'timestamp|url',
356 ApiBase::PARAM_ISMULTI => true,
357 ApiBase::PARAM_HELP_MSG => 'apihelp-query+imageinfo-param-prop',
358 ApiBase::PARAM_HELP_MSG_PER_VALUE =>
359 ApiQueryImageInfo::getPropertyMessages( $this->propertyFilter ),
360 ],
361 'prefix' => null,
362 'minsize' => [
363 ApiBase::PARAM_TYPE => 'integer',
364 ],
365 'maxsize' => [
366 ApiBase::PARAM_TYPE => 'integer',
367 ],
368 'sha1' => null,
369 'sha1base36' => null,
370 'user' => [
371 ApiBase::PARAM_TYPE => 'user'
372 ],
373 'filterbots' => [
374 ApiBase::PARAM_DFLT => 'all',
375 ApiBase::PARAM_TYPE => [
376 'all',
377 'bots',
378 'nobots'
379 ]
380 ],
381 'mime' => [
382 ApiBase::PARAM_ISMULTI => true,
383 ],
384 'limit' => [
385 ApiBase::PARAM_DFLT => 10,
386 ApiBase::PARAM_TYPE => 'limit',
387 ApiBase::PARAM_MIN => 1,
388 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
389 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
390 ],
391 ];
392
393 if ( $this->getConfig()->get( 'MiserMode' ) ) {
394 $ret['mime'][ApiBase::PARAM_HELP_MSG] = 'api-help-param-disabled-in-miser-mode';
395 }
396
397 return $ret;
398 }
399
400 private $propertyFilter = [ 'archivename', 'thumbmime', 'uploadwarning' ];
401
402 protected function getExamplesMessages() {
403 return [
404 'action=query&list=allimages&aifrom=B'
405 => 'apihelp-query+allimages-example-B',
406 'action=query&list=allimages&aiprop=user|timestamp|url&' .
407 'aisort=timestamp&aidir=older'
408 => 'apihelp-query+allimages-example-recent',
409 'action=query&list=allimages&aimime=image/png|image/gif'
410 => 'apihelp-query+allimages-example-mimetypes',
411 'action=query&generator=allimages&gailimit=4&' .
412 'gaifrom=T&prop=imageinfo'
413 => 'apihelp-query+allimages-example-generator',
414 ];
415 }
416
417 public function getHelpUrls() {
418 return 'https://www.mediawiki.org/wiki/API:Allimages';
419 }
420 }